//
//  HMUserAccessModel.swift
//  swift一遍敲
//
//  Created by 刘耀宗 on 16/4/19.
//  Copyright © 2016年 刘耀宗. All rights reserved.
//

import UIKit

class HMUserAccessModel: NSObject {
    //定义一个归档路径
    var pathField = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    //创建一个单例
    static let shareAccessModel: HMUserAccessModel = HMUserAccessModel()
    var userAccess: accessTokenModel?
    override init() {
        super.init()
        //先获取
        userAccess = loadAccessUser()
    }
    var login: Bool?
        {
        get {
        return userAccess != nil
        
        }
    
    
    }
    
    
    //加载数据
    func loadUserAcessToken(code: String,backallocate: (error: NSError?) -> ())
    {
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type":"authorization_code",
            "redirect_uri": redirect_uri,
            "code": code
            
            
        ]
        HMAFNTool.shareAfnwork.POST(accessTokenURLString, parameters: parameters, success: { (task, responseObject) -> Void in
            //加载数据成功
            
            let result = responseObject as? [String: AnyObject]
            if let dict = result
            {
                self.userAccess = accessTokenModel.init(dict: dict)
               print("加载数据成功")
                
                //保存数据
                self.saveAccessCount()
                
                print("access_token= \(self.userAccess?.access_token)")
                
//                self.loadUserInfo({ 
//                    
//                })
//          
                //通知控制器做事
                backallocate(error: nil)
            
            
            }
            
            }, failure: { (task, error) in
                print("加载数据失败")
                backallocate(error: error)
        })
    
    
    
    }
    
    //存储数据
   private func saveAccessCount()
    {
        if let userAccess = self.userAccess
        {
            NSKeyedArchiver.archiveRootObject(userAccess, toFile: pathField)
        }
    }
    //解档账号
    private func loadAccessUser() -> accessTokenModel?
    {
        let userAccout = NSKeyedUnarchiver.unarchiveObjectWithFile(pathField) as? accessTokenModel
        
        
        return userAccout
        
        
        
    }
    
    func loadUserInfo(backallocate: (error: NSError?) -> ())
    {
        let urlStr = "https://api.weibo.com/2/users/show.json"
        guard let access_token = loadAccessUser()?.access_token
        else{
        
            print("access_token为空")
            return
        
        }
    
       guard let uid = self.userAccess?.uid
        else{
            print("uid为空")
            return
        
        
        }
      
        
            let  parame = [
                "access_token" : access_token,
                "uid" : uid
                
            ]
            
            HMAFNTool.shareAfnwork.GET(urlStr, parameters: parame, success: { (task, responseObject) in
                print("responseObject = \(responseObject)")
                let dict = responseObject as? [String: AnyObject]
                self.userAccess?.screen_name = dict!["screen_name"] as? String
                self.userAccess?.avatar_large = dict!["avatar_large"] as? String
                
                print("名字是 \(self.userAccess?.screen_name)")
                print("加载token成功")
                self.saveAccessCount()
                backallocate(error:  nil)
                
                }) { (task, error) in
                     print("加载token失败")
                     backallocate(error: error)
                    
            }
            
            

            
            
        }

    
    
 
    

}
